package com.donleo.oauth2.uaa.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.donleo.oauth2.common.model.Permission;
import com.donleo.oauth2.common.model.User;
import com.donleo.oauth2.uaa.service.UserService;
import com.donleo.oauth2.uaa.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author liangd
 * @since 2021-03-10 14:27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findUserByUsername(String username) {
        return lambdaQuery().eq(User::getUsername, username).one();
    }

    @Override
    public List<String> findPermissionByUserId(Long userId) {
        List<Permission> list = userMapper.findPermissionByUserId(userId);
        List<String> permissions = new ArrayList<>();
        list.forEach(permission -> permissions.add(permission.getValue()));
        return permissions;
    }

    @Override
    public String register(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setCreateTime(new Date());
        user.setStatus(1);
        int i = userMapper.insert(user);
        return i > 0 ? "注册成功" : "注册失败";
    }
}
